<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'srm:cw:billvouch:puBillVouch:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #puBillVouchsList>
        <BasicTable @register="registerPuBillVouchsTable" @row-click="handlePuBillVouchsRowClick" @edit-change="rowChange"/>
        <!-- <a-button
          class="mt-2"
          @click="handlePuBillVouchsAdd"
          v-auth="'srm:cw:billvouch:puBillVouch:edit'"
        >
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button> -->
      </template>
    </BasicForm>
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="Flow_Srm_Pu_Bill_Vouch"
        completeText="提交"
        :completeModal="true"
        :loading="loadingRef"
        :auth="'srm:cw:billvouch:puBillVouch:edit'"
        @validate="handleValidate"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsSrmCwBillvouchPuBillVouchForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    PuBillVouch,
    puBillVouchSave,
    puBillVouchForm,
    puBillVouchCalcMoney
  } from '/@/api/srm/cw/billvouch/puBillVouch';
  import { NumEnum } from '/@/enums/defEnum';
  import { BpmButton } from '/@/components/Bpm';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('srm/cw.billvouch.puBillVouch');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<PuBillVouch>({} as PuBillVouch);
  const loadingRef = ref(false);

  let kpStatus = ref('')

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    // value: record.value.isNewRecord ? t('新增开票清单') : t('编辑开票清单'),
    value: t('开票通知单'),
  }));

  const inputFormSchemas: FormSchema[] = [
     {
      label: t('基本信息'),
      field: 'info1',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('单据号'),
      field: 'djno',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
      dynamicDisabled: true,
    },
    {
      label: t('公司'),
      field: 'company.companyName',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
      dynamicDisabled: true,
    },
    {
      label: t('供应商'),
      field: 'basVen.cusname',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
      dynamicDisabled: true,
    },
    {
      label: t('公司'),
      field: 'pkCorp',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
      show:false
    },
    {
      label: t('供应商'),
      field: 'venId',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
      show:false
    },
    {
      label: t('单据日期'),
      field: 'ddate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        // showTime: { format: 'HH:mm' },
      },
      dynamicDisabled: true,
    },
    {
      label: t('备注信息'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
        disabled:computed(() => kpStatus.value != '5'&& kpStatus.value != '6' && kpStatus.value != '9')
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('合计信息'),
      field: 'info2',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('价税合计'),
      field: 'itaxmoney',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [
        { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      ],
      dynamicDisabled: true,
    },
    {
      label: t('税额'),
      field: 'itax',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [
        { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      ],
      dynamicDisabled: true,
    },
    {
      label: t('无税金额'),
      field: 'imoney',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [
        { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      ],
      dynamicDisabled: true,
    },
    {
      label: t('币种'),
      field: 'currtypename',
      component: 'Input',
      componentProps: {
        maxlength: 50,
      },
      dynamicDisabled: true,
    },
    // {
    //   label: t('打印次数'),
    //   field: 'prtQty',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 8,
    //   },
    //   rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    //   dynamicDisabled: true,
    // },
   
    {
      label: t('开票明细'),
      field: 'info3',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t(''),
      field: 'puBillVouchsList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'puBillVouchsList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerPuBillVouchsTable, puBillVouchsTable] = useTable({
    actionColumn: {
      ifShow:() => kpStatus.value == '5' || kpStatus.value == '6' || kpStatus.value == '9' ,
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'i-ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handlePuBillVouchsDelete.bind(this, record),
          },
          auth: 'srm:cw:billvouch:puBillVouch:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setPuBillVouchsTableData(_res: Recordable) {
    puBillVouchsTable.setColumns([
      {
        title: t('入库单号'),
        dataIndex: 'vbillcode',
        width: 130,
        align: 'left',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 100,
        // },
        // editRule: true,
      },
      {
        title: t('入库行号'),
        dataIndex: 'crowno',
        width: 80,
        align: 'center',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 100,
        // },
        // editRule: false,
      },
      {
        title: t('入库日期'),
        dataIndex: 'dbilldate',
        width: 100,
        align: 'center',
        // editRow: true,
        // editComponent: 'DatePicker',
        // editComponentProps: {
        //   format: 'YYYY-MM-DD HH:mm',
        //   showTime: { format: 'HH:mm' },
        // },
        // editRule: false,
      },
      {
        title: t('仓库名称'),
        dataIndex: 'wareName',
        width: 130,
        align: 'left',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 50,
        // },
        // editRule: false,
      },
      {
        title: t('订单号'),
        dataIndex: 'orerCode',
        width: 130,
        align: 'left',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 64,
        // },
        // editRule: false,
      },
      {
        title: t('存货基本ID'),
        dataIndex: 'invId',
        width: 130,
        align: 'left',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 64,
        // },
        // editRule: false,
        ifShow: false,
      },
      {
        title: t('存货编码'),
        dataIndex: 'cinvcode',
        width: 130,
        align: 'left',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 64,
        // },
        // editRule: true,
      },
      {
        title: t('存货名称'),
        dataIndex: 'cinvname',
        width: 130,
        align: 'left',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 64,
        // },
        // editRule: true,
      },
      {
        title: t('规格'),
        dataIndex: 'cinvspec',
        width: 130,
        align: 'left',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 100,
        // },
        // editRule: false,
      },
      {
        title: t('型号'),
        dataIndex: 'cinvtype',
        width: 130,
        align: 'left',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 100,
        // },
        // editRule: false,
      },
      {
        title: t('单位名称'),
        dataIndex: 'measname',
        width: 80,
        align: 'left',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 50,
        // },
        // editRule: false,
      },
      {
        title: t('开票数量'),
        dataIndex: 'iqty',
        width: 100,
        align: 'center',
        // editRow: true,
        editRow: kpStatus.value == '5' || kpStatus.value == '6' || kpStatus.value == '9'?true:false,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 16,
          min:0,
          disabled:true
        },
        editRule: true,
      },
      {
        title: t('无税单价'),
        dataIndex: 'nprice',
        width: 100,
        align: 'center',
        // editRow: true,
        editRow: kpStatus.value == '5' || kpStatus.value == '6' || kpStatus.value == '9'?true:false,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 16,
          min:0
        },
        editRule: false,
      },
      {
        title: t('无税金额'),
        dataIndex: 'nmny',
        width: 100,
        align: 'center',
        // editRow: true,
        editRow: kpStatus.value == '5' || kpStatus.value == '6' || kpStatus.value == '9'?true:false,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 16,
          min:0
        },
        editRule: false,
      },
      {
        title: t('含税单价'),
        dataIndex: 'ntaxprice',
        width: 100,
        align: 'center',
        // editRow: true,
        editRow: kpStatus.value == '5' || kpStatus.value == '6' || kpStatus.value == '9'?true:false,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 16,
          min:0
        },
        editRule: false,
      },
      {
        title: t('含税金额'),
        dataIndex: 'ntaxmny',
        width: 100,
        align: 'center',
        // editRow: true,
        editRow: kpStatus.value == '5' || kpStatus.value == '6' || kpStatus.value == '9'?true:false,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 16,
          min:0
        },
        editRule: false,
      },
      {
        title: t('税率'),
        dataIndex: 'nictaxrate',
        width: 100,
        align: 'center',
        // editRow: kpStatus.value == '5' || kpStatus.value == '6' || kpStatus.value == '9'?true:false,
        // editComponent: 'InputNumber',
        // editComponentProps: {
        //   maxlength: 16,
        //   min:0
        // },
        // editRule: false,
      },
      {
        title: t('税额'),
        dataIndex: 'noritaxmny',
        width: 100,
        align: 'center',
        editRow: kpStatus.value == '5' || kpStatus.value == '6' || kpStatus.value == '9'?true:false,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 16,
          disabled:true
        },
        editRule: false,
      },
      {
        title: t('备注'),
        dataIndex: 'remarks',
        width: 150,
        align: 'left',
        // editRow: true,
        editRow: kpStatus.value == '5' || kpStatus.value == '6' || kpStatus.value == '9'?true:false,
        editComponent: 'InputTextArea',
        editComponentProps: {
          maxlength: 500,
        },
        editRule: false,
      },
      {
        title: t('批注'),
        dataIndex: 'auditRemarks',
        width: 150,
        align: 'left',
        // editRow: true,
        editRow: kpStatus.value == '5' || kpStatus.value == '6' || kpStatus.value == '9'?true:false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 500,
        },
        editRule: false,
      },
    ]);
    puBillVouchsTable.setTableData(record.value.puBillVouchsList || []);
  }

  function handlePuBillVouchsRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handlePuBillVouchsAdd() {
    puBillVouchsTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handlePuBillVouchsDelete(record: Recordable) {
    puBillVouchsTable.deleteTableDataRecord(record);
  }

  async function getPuBillVouchsList() {
    let puBillVouchsListValid = true;
    let puBillVouchsList: Recordable[] = [];
    for (const record of puBillVouchsTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        puBillVouchsListValid = false;
      }
      puBillVouchsList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of puBillVouchsTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      puBillVouchsList.push({
        ...record,
        status: '1',
      });
    }
    if (!puBillVouchsListValid) {
      throw { errorFields: [{ name: ['puBillVouchsList'] }] };
    }
    return puBillVouchsList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await puBillVouchForm(data);
    record.value = (res.puBillVouch || {}) as PuBillVouch;
    record.value.__t = new Date().getTime();
 
    kpStatus.value = record.value.status
    setFieldsValue(record.value);
    setPuBillVouchsTableData(res);
    updateSchema([
      {
        field: 'djno',
        componentProps: {
          disabled: !record.value.isNewRecord,
        },
      },
    ]);
    setDrawerProps({ loading: false });
  });

  async function handleValidate(_event: any, formData: any) {
    try {
      const data = await validate();
      formData(true, data); // 将表单数据传递给 BpmButton
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    }
  }

  async function handleSubmit(event: any) {
    try {
      loadingRef.value = true;
      // const data = event?.formData || (await validate()); // 接受 BpmButton 传递过来的表单数据
      const data =await validate(); // 接受 BpmButton 传递过来的表单数据
      data.bpm = Object.assign(data.bpm || {}, record.value.bpm); // 流程信息
      data.status = record.value.status; // 提交状态
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        djno: record.value.djno,
      };
      // data.puBillVouchsList = await getPuBillVouchsList();
      if(kpStatus.value != '5' && kpStatus.value != '6' && kpStatus.value != '9'){
        data.puBillVouchsList = record.value.puBillVouchsList
      }else{
        data.puBillVouchsList = await getPuBillVouchsList();
      }
      // console.log('submit', params, data, record);
      const res = await puBillVouchSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }


  async function rowChange({ column, value, record }) {
    let {
      editValueRefs: { iqty, nprice, nmny, ntaxprice, ntaxmny,noritaxmny },
    } = record;
    if (column.dataIndex == 'iqty') {

      iqty.value = value.toFixed(NumEnum.scaleSelQty);
      if(value == 0){
        return;
      }
      // 开票数
      let data = {
        iqty: iqty.value,
        fprice: nprice.value,
        fmoney: nmny.value,
        ftaxPrice: ntaxprice.value,
        ftaxMoney: ntaxmny.value,

        ftaxRate: record.nictaxrate,
        ftax: noritaxmny.value,
        updateType: 'iqty',
      }
      let res = await puBillVouchCalcMoney(data)
      nprice.value = res.data.fprice
      nmny.value = res.data.fmoney
      ntaxprice.value = res.data.ftaxPrice
      ntaxmny.value = res.data.ftaxMoney

      noritaxmny.value = res.data.ftax
    }

    if (column.dataIndex == 'nprice') {
      nprice.value = value.toFixed(NumEnum.scaleSelQty);
      // 无税单价
      let data = {
        iqty: iqty.value,
        fprice: nprice.value,
        fmoney: nmny.value,
        ftaxPrice: ntaxprice.value,
        ftaxMoney: ntaxmny.value,

        ftaxRate: record.nictaxrate,
        ftax: noritaxmny.value,
        updateType: 'fprice',
      }
      let res = await puBillVouchCalcMoney(data)
      // nprice.value = res.data.fprice
      nmny.value = res.data.fmoney
      ntaxprice.value = res.data.ftaxPrice
      ntaxmny.value = res.data.ftaxMoney

      noritaxmny.value = res.data.ftax
    }

    if (column.dataIndex == 'nmny') {
      nmny.value = value.toFixed(NumEnum.scaleSelQty);
      // 无税金额
      let data = {
        iqty: iqty.value,
        fprice: nprice.value,
        fmoney: nmny.value,
        ftaxPrice: ntaxprice.value,
        ftaxMoney: ntaxmny.value,

        ftaxRate: record.nictaxrate,
        ftax: noritaxmny.value,
        updateType: 'fmoney',
      }
      let res = await puBillVouchCalcMoney(data)
      nprice.value = res.data.fprice
      // nmny.value = res.data.fmoney
      ntaxprice.value = res.data.ftaxPrice
      ntaxmny.value = res.data.ftaxMoney

      noritaxmny.value = res.data.ftax
    }

    if (column.dataIndex == 'ntaxprice') {
      ntaxprice.value = value.toFixed(NumEnum.scaleSelQty);
      // 含税单价
      let data = {
        iqty: iqty.value,
        fprice: nprice.value,
        fmoney: nmny.value,
        ftaxPrice: ntaxprice.value,
        ftaxMoney: ntaxmny.value,

        ftaxRate: record.nictaxrate,
        ftax: noritaxmny.value,
        updateType: 'ftaxPrice',
      }
      let res = await puBillVouchCalcMoney(data)
      nprice.value = res.data.fprice
      nmny.value = res.data.fmoney
      // ntaxprice.value = res.data.ftaxPrice
      ntaxmny.value = res.data.ftaxMoney

      noritaxmny.value = res.data.ftax
    }

    if (column.dataIndex == 'ntaxmny') {
      ntaxmny.value = value.toFixed(NumEnum.scaleSelQty);
      // 含税金额
      let data = {
        iqty: iqty.value,
        fprice: nprice.value,
        fmoney: nmny.value,
        ftaxPrice: ntaxprice.value,
        ftaxMoney: ntaxmny.value,

        ftaxRate: record.nictaxrate,
        ftax: noritaxmny.value,
        updateType: 'ftaxMoney',
      }
      let res = await puBillVouchCalcMoney(data)
      nprice.value = res.data.fprice
      nmny.value = res.data.fmoney
      ntaxprice.value = res.data.ftaxPrice
      // ntaxmny.value = res.data.ftaxMoney

      noritaxmny.value = res.data.ftax
    }
  }
</script>
